package com.onion.mvc.resolver.builder;

import com.alibaba.fastjson.JSON;
import com.onion.mvc.enums.ParamPolicy;
import com.onion.mvc.utils.WebRequestUtils;
import com.onion.utils.surface.request.Request;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;

public class BodyOnlyParamBuilder implements RequestParamBuilder {

    @Override
    public ParamPolicy mode() {
        return ParamPolicy.BODY_ONLY;
    }

    @Override
    public Request build(NativeWebRequest webRequest, MethodParameter parameter) {
        HttpServletRequest httpRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String body = null;
        if("post".equals(httpRequest.getMethod().toLowerCase())){
            body = WebRequestUtils.getBodyData(httpRequest);
        }
        return (Request) (JSON.parseObject(body, parameter.getParameterType()));
    }

}